package naga.x.platform2.channel.j9kgames;

import java.util.Map;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import naga.x.platform2.app.Channel;
import naga.x.platform2.app.model.GameServer;
import naga.x.platform2.app.model.Recharge;
import naga.x.platform2.app.model.RechargeTemplate;
import naga.x.platform2.app.support.GameServerSupport;
import naga.x.platform2.app.support.RechargeSupport;
import naga.x.platform2.channel.j9kgames.support.J9KGamesApi;
import naga.x.platform2.channel.j9kgames.support.J9KGamesConfig;
import naga.x.platform2.support.RequestPath;
import naga.x.platform2.utils.HttpUtils;
import naga.x.platform2.utils.NumberUtils;
import naga.x.platform2.utils.StringUtils;

/**
 * 游戏金榜
 * @see <a href="https://dev.99kgames.com/gameApi/index/partnerid/aad2ac3ebbccd039ea8600d20b9feea8">游戏金榜技术对接-万家</a>
 * @author yang.li
 *
 */
@Controller
public class J9KGamesController {

	@Autowired
	private J9KGamesConfig config;
	@Autowired
	private J9KGamesApi api;
	@Autowired
	private RechargeSupport support;
	@Autowired
	private GameServerSupport gameServers;
	
	private static Channel channel = Channel.J9KGAMES;
	
	public static final Logger LOG = LoggerFactory.getLogger(J9KGamesController.class);
	
	@RequestMapping(path = RequestPath.J9KGAMES_USER_INFO, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object getUser(String token) {
		String url = J9KGamesApi.URL_GET_USER;
		Map<String, String> params = new TreeMap<String, String>();
//		partnerid: 厂商编号，由游戏金榜提供
//		access_token: 加载游戏的链接上带的access_token参数
//		sign:请求签名，参考请求参数签名方式
		params.put("access_token", token);
		params.put("partnerid", config.getPartnerId());
		params.put("sign", api.makeSign(params));
		
//		code: 请求状态，0表示请求成功。
//		message: 接口错误信息。请求成功时为OK
//		userid: 用户唯一标识
//		nickname: 用户昵称
//		avatar : 用户头像地址
//		sex : 用户的性别。0:未知，1:男性，2:女性
//		province: 用户所在的省份
//		city:用户所在的城市
//		invitor: 邀请者。没有邀请者为0，有邀请者，为邀请者的userid
		String s = HttpUtils.post(url, params);
//		JSONObject res = JSON.parseObject(s);
		return s;
	}
	
	@RequestMapping(path = RequestPath.J9KGAMES_SUBSCRIBE, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object subscribe(String uid) {
//		http://api.99kgames.com/vendor/api/subscribe
//			调用参数
//			user_identify:用户8位标志
//			partnerid:厂商编号
//			sign:签名, 签名规则在文档末尾
		Map<String, String> params = new TreeMap<String, String>();
		params.put("user_identify", uid);
		params.put("partnerid", config.getPartnerId());
		params.put("sign", api.makeSign(params));
//		code: 请求状态，0表示请求成功，其他值表示失败
//		message: 字符串类型, 1 表示关注 ，0 表示未关注
		return HttpUtils.post(J9KGamesApi.URL_SUBSCRIBE, params);
	}
	
	@RequestMapping(path = RequestPath.J9KGAMES_PAY, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object pay(Integer sid, Long pid, Integer product) {
		GameServer gs = gameServers.get(sid);
		if (gs == null) {
			return api.makeOrderErrorResponse("服务器id错误");
		}
		if (pid == null) {
			return api.makeOrderErrorResponse("玩家id错误");
		}
		RechargeTemplate template = support.getTemplate(product);
		if (template == null) {
			return api.makeOrderErrorResponse("充值id错误");
		}
		return api.makeOrderResponse(template, sid, pid);
	}
	
	/**
	 * 支付回调（由游戏金榜调用）
	 * 
	 * @param trade_status 支付状态。目前固定为SUCCESS，表示支付成功
	 * @param game 游戏代号。游戏的唯一标识，提前约定好的代号
	 * @param partnerid 厂商编号。厂商唯一标识，由游戏金榜提供
	 * @param userid 用户标识。 用户唯一标识，一般为8位数字 
	 * @param total_fee 总金额。订单总金额，以分为单位
	 * @param transaction_id 交易编号。该笔支付在游戏金榜的交易单号，每笔支付唯一
	 * @param out_trade_no 厂商订单编号。厂商发起支付时填写的订单编号
	 * @param product_id 厂商商品编号。厂商发起支付时填写的商品id
	 * @param attach 厂商附加数据。厂商发起支付时填写的附加数据
	 * @param pay_time 支付时间。用户支付成功的时间,“年月日时分秒”不带空格的格式：20160401112007
	 * @param timestamp 通知时间。发起支付通知的时间，以秒为单位
	 * @param sign 请求参数签名。所有请求参数的签名，参考后台接口签名方式
	 * @return success/错误信息
	 */
	@RequestMapping(path = RequestPath.J9KGAMES_PAY_CALLBACK, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object payCallback(String trade_status, String game, String partnerid, String userid, String total_fee, String transaction_id, String out_trade_no, String product_id, String attach, String pay_time, String timestamp, String sign) {
		Map<String, String> params = new TreeMap<>();
		params.put("trade_status", trade_status);
		params.put("game", game);
		params.put("partnerid", partnerid);
		params.put("userid", userid);
		params.put("total_fee", total_fee);
		params.put("transaction_id", transaction_id);
		params.put("out_trade_no", out_trade_no);
		params.put("product_id", product_id);
		params.put("attach", attach);
		params.put("pay_time", pay_time);
		params.put("timestamp", timestamp);
		String s = api.makeSign(params);
		if (!s.equals(sign)) {
			params.put("sign", sign);
			LOG.info("[99KGAMES PAY ERR]PARAMS[{}]SIGN[{}]CAUSE[SIGNERR]", params, s);
			return "sign error";
		}
		
		try {
			String[] strs = StringUtils.split(attach, "|");
			int serverId = NumberUtils.parseInt(strs[0]);
			long playerId = NumberUtils.parseLong(strs[1]);
			RechargeTemplate template = support.getTemplate(NumberUtils.parseInt(product_id));
			Recharge r = new Recharge(channel.prefix + transaction_id, playerId, serverId,
					(int) (NumberUtils.parseDouble(total_fee) / 100), template.getStone(), template.getId(), channel.name);
			r.setAttach(out_trade_no); // 我方订单号
			r.setChannelUid(channel.withPrefix(userid));
			support.offer(r);
			LOG.info("[99KGAMES PAY SUCC]PARAMS[{}]", params);
		} catch (Exception e) {
			LOG.error("[99KGAMES PAY ERR]PARAMS[" + params + "]CAUSE[EXCEPTION]", e);
		}
		
		return "success";
	}
	
}
